//
//  HeaderDragLayout.swift
//  CTCollectionViewDemo
//
//  Created by GodCoder on 2019/8/6.
//  Copyright © 2019 CTCollectionView. All rights reserved.
//

import UIKit

class HeaderDragLayout: UICollectionViewFlowLayout {

    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        let layoutAttributes = super.layoutAttributesForElements(in: rect)
        for layout in layoutAttributes! {
            /** 1.判断是否是头部视图 */
            if layout.representedElementKind == UICollectionView.elementKindSectionHeader {
                let contentOffSetY: CGFloat = self.collectionView?.contentOffset.y ?? 0
                /** 2.判断是否下拉 */
                if contentOffSetY < CGFloat(0) {
                    /** 3.重新设置头部视图的起始位置和高度 */
                    layout.frame = CGRect(x: layout.frame.minX, y: contentOffSetY, width: layout.frame.width, height: layout.frame.height - contentOffSetY)
                }
            }
        }
        return layoutAttributes
    }
    
    override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
        return true
    }
}
